package main

import (
	"awesomeProject/httpserver/handler"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
)

type HttpHandler func(writer http.ResponseWriter, request *http.Request) error

type userError interface {
	error
	Message() string
}

func errWrapper(handler HttpHandler) func(writer http.ResponseWriter, request *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {
		if err := handler(writer, request); err != nil {
			code := http.StatusOK
			switch {
			case os.IsNotExist(err):
				code = http.StatusNotFound
			case os.IsPermission(err):
				code = http.StatusForbidden
			default:
				code = http.StatusInternalServerError
			}
			fmt.Println(err)
			if err, ok := err.(userError); ok == true {
				http.Error(writer, err.Error(), http.StatusBadRequest)
			}
			http.Error(writer, http.StatusText(code), code)
		}
		httptest.NewRecorder()
	}
}

func main() {
	http.HandleFunc("/", errWrapper(handler.HandleHttp))
	err := http.ListenAndServe(":8888", nil)
	if nil != err {
		panic(err)
	}
}
